package com.keon.jianbao.wxapi;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.keon.jianbao.AppContext;
import com.keon.jianbao.R;
import com.keon.jianbao.api.Api;
import com.keon.jianbao.api.WXApi;
import com.keon.jianbao.bean.Result;
import com.keon.jianbao.bean.User;
import com.keon.jianbao.bean.WXToken;
import com.keon.jianbao.bean.WXUser;
import com.keon.jianbao.ui.activity.LoginActivity;
import com.keon.jianbao.ui.activity.MainActivity;
import com.keon.jianbao.util.JsonUtils;
import com.keon.jianbao.util.StringUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;

import org.apache.http.Header;
import org.json.JSONException;

public class WXEntryActivity2 extends Activity implements IWXAPIEventHandler {
    private Context context = WXEntryActivity2.this;

    AsyncHttpResponseHandler alterInfoHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
//                    Toast.makeText(WXEntryActivity.this, result.getTips(), Toast.LENGTH_LONG).show();

                } else {
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            Toast.makeText(WXEntryActivity2.this, R.string.common_error_network, Toast.LENGTH_LONG).show();
        }
    };

    AsyncHttpResponseHandler userInfoHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            WXUser wxUser = JsonUtils.fromJson(new String(responseBody), WXUser.class);
            String openid = wxUser.getOpenid();
            if (!StringUtils.isEmpty(openid)) {
                Api.alter_info(AppContext.getInstance().getProperty("user.code"), "", wxUser.getNickname(),
                        wxUser.getProvince() + wxUser.getCity(), wxUser.getSexText(), "", wxUser.getHeadimgurl(),
                        alterInfoHandler);
            } else {
                Toast.makeText(WXEntryActivity2.this, R.string.common_error_network, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            Toast.makeText(WXEntryActivity2.this, R.string.common_error_network, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFinish() {
            WXEntryActivity2.this.finish();
        }
    };

    AsyncHttpResponseHandler wxBindHanlder = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            try {
                Result result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    User user = JsonUtils.fromJson(result.getContent(), User.class);
                    AppContext.saveUserInfo(user);
                    AppContext.saveCookies(headers);

                    if (StringUtils.isEmpty(user.getUser_name())) {
                        WXApi.WXUserinfo(AppContext.getInstance().getProperty("wx.access_token"),
                                AppContext.getInstance().getProperty("wx.openid"), userInfoHandler);
                    }

                    Toast.makeText(WXEntryActivity2.this, "登录成功", Toast.LENGTH_LONG).show();
                    Intent intent = new Intent();
                    intent.setClass(WXEntryActivity2.this, MainActivity.class);
                    startActivity(intent);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//            String result = new String(responseBody);
            Toast.makeText(WXEntryActivity2.this, R.string.common_error_network, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFinish() {
            super.onFinish();
            WXEntryActivity2.this.finish();
        }
    };

    AsyncHttpResponseHandler wxAccessTokenHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            WXToken wxToken = JsonUtils.fromJson(result, WXToken.class);

            String openid = wxToken.getOpenid();
            if (!StringUtils.isEmpty(openid)) {
                AppContext.saveWX(wxToken);
                Api.async_login_auto(openid, LoginActivity.TYPE_WX, wxBindHanlder);

            } else {
                Toast.makeText(WXEntryActivity2.this, R.string.common_error_network, Toast.LENGTH_LONG).show();
            }


        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//            String result = new String(responseBody);
            Toast.makeText(WXEntryActivity2.this, R.string.common_error_network, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFinish() {
            super.onFinish();
            WXEntryActivity2.this.finish();
        }
    };

    private void handleIntent(Intent paramIntent) {
        AppContext.WXapi.handleIntent(paramIntent, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntent(intent);
    }

    @Override
    public void onReq(BaseReq arg0) {
// TODO Auto-generated method stub
        finish();
    }

    @Override
    public void onResp(BaseResp resp) {
// TODO Auto-generated method stub
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                String code = ((SendAuth.Resp) resp).code;
                if (ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX == resp.getType()) {
                    Toast.makeText(context, "分享成功", Toast.LENGTH_LONG).show();
                    break;
                }
                if (ConstantsAPI.COMMAND_SENDAUTH == resp.getType()) {
                    WXApi.getWXAccessToken(code, wxAccessTokenHandler);
                }



             /*   Message message = new Message();
                message.what = LoginActivity.TYPE_WX;
                Bundle bundle = new Bundle();
                bundle.putString("code", code);
                message.setData(bundle);
                LoginActivity.thirdLoginHandler.sendMessage(message);*/

                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                break;
            default:
                break;
        }
//        finish();
    }
}